/****************************************************************************
 *
 * Copyright (C) 2003-2008 Los Alamos National Security, LLC
 *                         Packet Analytics Corporation
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License Version 2 as
 * published by the Free Software Foundation.  You may not use, modify or
 * distribute this program under any other version of the GNU General
 * Public License.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
 *
 ****************************************************************************/
package nfse.gui.client.alert;

import java.util.Vector;

import nfse.gui.client.EventDisplayDialog;
import nfse.gui.client.EventViewerDialog;
import nfse.gui.client.NetFSEClient;
import nfse.gui.client.reports.TopValues;
import nfse.gui.query.*;
import nfse.gui.client.alert.*;
import nfse.gui.client.TestDialog;
import nfse.gui.record.FlexRecord;
import nfse.gui.record.FlexRecordField;
import nfse.gui.util.NetUtil;
import com.gwtext.client.widgets.MessageBox;
import com.gwtext.client.widgets.MessageBoxConfig;
import com.google.gwt.core.client.*;
import com.google.gwt.user.client.*;
import com.google.gwt.user.client.ui.*;
import com.google.gwt.user.client.rpc.*;

public class AlertTab extends FlexTable {
    NetFSEClient client = null;

    // FlexTable browseTable = new FlexTable();

    private EventDisplayDialog eventDisplayDialog = new EventDisplayDialog();

    private FlexTable dataTable = new FlexTable();

    // private DeleteDialogBox deleteDialog = null;

    private Hyperlink deleteLink = new Hyperlink();

    private Hyperlink exportLink = new Hyperlink();

    private Hyperlink firstLink = new Hyperlink();

    private Hyperlink lastLink = new Hyperlink();

    private CheckBox messageCheckBox = new CheckBox("Alert");

    private CheckBox dstipCheckBox = new CheckBox("Dst IP");

    private CheckBox srcipCheckBox = new CheckBox("Src IP");

    private CheckBox srcportCheckBox = new CheckBox("Src Port");

    private CheckBox dstportCheckBox = new CheckBox("Dst Port");

    private CheckBox protocolCheckBox = new CheckBox("Protocol");

    private int n = 15;

    private Hyperlink nextLink = new Hyperlink();

    private int offsets = 0;

    private AlertOptionsDialog optionDialog2 = null;
    
    private Hyperlink optionLink = new Hyperlink();

    private String orderBy = new String();

    private Hyperlink prevLink = new Hyperlink();

    private int recordCount = 0;

    private Hyperlink refreshSummaryLink = new Hyperlink();

    private String schema = "";

    private Hyperlink showHideLink = new Hyperlink();

    private Hyperlink showHideSummaryLink = new Hyperlink();

    private Label statusLabel = new Label();

    private FlexTable summaryDataTable = new FlexTable();

    FlexTable summaryHeaderTable = new FlexTable();

    private Label summaryStatusLabel = new Label();

    FlexTable summaryTable = new FlexTable();

    FlexTable[] summaryTableByField = new FlexTable[0];

    private FlexTable table = new FlexTable();

    private String where = new String();

    public AlertTab(NetFSEClient client) {
        this.client = client;
        setTypes();
        get(0);
        summary();
    }

    private void clearTable() {
        FlexTable table = getDataTable();
        if (table != null)
            while (table.getRowCount() > 1)
                table.removeRow(1);
    }

    private void delete(String sql) {

        AlertServiceAsync NetFSEService = (AlertServiceAsync) GWT.create(AlertService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) NetFSEService;
        endpoint.setServiceEntryPoint(AlertService.URL);

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirect("NetFSEClient.html");
            }

            public void onSuccess(Object result) {
                get(0);
            }
        };

        NetFSEService.delete(sql, callback);

    }

    public int getRecordCount() {
        return recordCount;
    }

    public String getSchema() {
        return schema;
    }

    private void get(int offset) {

        if (offset > getRecordCount())
            offset = 0;

        final int n = getN();

        final int tempOffset = offset;
        final int count = getRecordCount();
        AlertServiceAsync nfseService = (AlertServiceAsync) GWT.create(AlertService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(AlertService.URL);

        AsyncCallback callback = new AsyncCallback() {

            public void onFailure(Throwable caught) {
                NetFSEClient.redirect("NetFSEClient.html");
                // clearTable(tempType);
            }

            public void onSuccess(Object result) {
                statusLabel.setText("Formatting data table; please wait");

                // if (getDataTable(tempType).getRowCount() > 1) {
                // return;
                // }

                QueryResult qr = (QueryResult) result;

                if (qr == null) {
                    String where = getWhere();
                    String orderBy = getOrderBy();
                    String str1 = "";
                    String str2 = "";
                    String title = "";
                    if (where.length() == 0 && orderBy.length() > 0) {
                        title = "Error in Order By Clause";
                        str1 = "Order By";
                        str2 = "<hr>Order By: <br><pre>" + orderBy + "</pre>";
                    } else if (where.length() > 0 && orderBy.length() == 0) {
                        title = "Error in Where Clause";
                        str1 = "Where";
                        str2 = "<hr>Where: <br><pre>" + where + "</pre>";
                    } else {
                        title = "Error in Where or Order By Clause";
                        str1 = "Where or Order By";
                        str2 = "<hr>Where: <br><pre>" + where + "</pre><hr>Order By: <br><pre>" + orderBy + "</pre>";
                    }
                    String html = "An error was returned by the server indicating an error in the " + str1
                            + " clause.<br>" + str2;
                    NetFSEClient.showGenericDialog(title, html);
                    statusLabel.setText("Error retrieving records. Check Where and Order By SQL in Options.");
                    clearTable();
                    return;

                }

                // for (int i = 0; i < NetForSEUtil.TYPE_NAMES.length; i++) {
                setRecordCount(qr.count);
                // }

                setOffset(tempOffset);
                int first = tempOffset + 1;
                int last = tempOffset + n;
                if (last > qr.count)
                    last = qr.count;

                // Record[] records = qr.records;

                // for (int i = 0; i < records.length; i++)
                // System.out.println(records[i]);
                showTable();
                if (qr.count == -1) {
                    clearTable();
                    statusLabel.setText("Data type not specified in original search.");
                    hideTable();
                    // System.out.println("Count is -1: " + tempType);
                } else {
                    updateTable(getTable(), getDataTable(), qr);
                    String status = "";
                    if (qr.alertFlexRecordGroup.records.length > 0) {
                        status = "Displaying records " + first + "-" + last + " of " + getRecordCount();
                        // schemas[typeIdxs[tempType]] = qr.schema;
                    } else
                        status = "No matching records found.";

                    statusLabel.setText(status);
                }
            }
        };
        statusLabel.setText("Retrieving records from database; please wait");

        nfseService.get(n, offset, getWhere(), getOrderBy(), callback);
    }

    private FlexTable getDataTable() {
        return dataTable;
    }

    public int getN() {
        return n;
    }

    public int getOffset() {
        return offsets;
    }

    public String getOrderBy() {
        return orderBy;
    }

    private void getTypeSummary(String[] fields, boolean updateHeader) {
        AlertServiceAsync nfseService = (AlertServiceAsync) GWT.create(AlertService.class);

        ServiceDefTarget endpoint = (ServiceDefTarget) nfseService;
        endpoint.setServiceEntryPoint(AlertService.URL);

        final String fieldName = "Alert";

        final FlexTable table = summaryTableByField[0];
        final boolean tempUpdateHeader = updateHeader;

        AsyncCallback callback = new AsyncCallback() {
            public void onFailure(Throwable caught) {
                NetFSEClient.redirect("NetFSEClient.html");
            }

            public void onSuccess(Object result) {

                summaryStatusLabel.setText("Request complete.");

                while (table.getRowCount() > 0)
                    table.removeRow(0);

                // showSummary(tempType);

                TopValues temp = (TopValues) result;

                if (tempUpdateHeader) {
                    initSummaryTable(summaryTable, summaryDataTable);
                    if (temp.values.length > 0) {
                        summaryTable.setHTML(1, 0, "<b>" + temp.startTS + " to " + temp.endTS + "</b>");
                    }
                }

                if (temp.values.length == 0) {
                    // //hideSummary(tempType);
                    return;
                } else {
                    //
                }

                table.setStyleName("nfsetable");
                table.addStyleName("nfsetbody");

                // table.getRowFormatter().setStyleName(0, "nfseth");

                FlexTable.FlexCellFormatter formatter = table.getFlexCellFormatter();

                int colSpan = 7 + temp.colNames.length;

                table.setHTML(0, 0, "<h3>Top " + fieldName + "s</h3>");
                formatter.setColSpan(0, 0, colSpan);
                formatter.addStyleName(0, 0, "tdcenter");

                int idx = -1;

                for (int i = 0; i < temp.colNames.length; i++) {
                    table.setHTML(1, ++idx, "<b>" + temp.colNames[i] + "</b>");
                    formatter.addStyleName(1, idx, "nfsetd");
                }

                table.setHTML(1, ++idx, "<b>Start</b>");
                formatter.addStyleName(1, idx, "nfsetd");
                table.setHTML(1, ++idx, "<b></b>");
                formatter.addStyleName(1, idx, "nfsetd");
                table.setHTML(1, ++idx, "<b>End</b>");
                formatter.addStyleName(1, idx, "nfsetd");
                table.setHTML(1, ++idx, "<b>Low</b>");
                formatter.addStyleName(1, idx, "nfsetd");
                table.setHTML(1, ++idx, "<b>High</b>");
                formatter.addStyleName(1, idx, "nfsetd");
                table.setHTML(1, ++idx, "<b>Total</b>");
                formatter.addStyleName(1, idx, "nfsetd");
                table.setHTML(1, ++idx, "<b>% Activity</b>");
                formatter.addStyleName(1, idx, "nfsetd");
                table.getRowFormatter().addStyleName(1, "nfseth");

                for (int i = 0; i < temp.values.length; i++) {
                    String html = "<img src=\"/nfse/spark?height=20&type=line&color=blue&data=";

                    // if (i % 2 == 0)
                    // dstIpSummaryTable.getRowFormatter().setStyleName(i + 2,
                    // "nfsetr");
                    // else
                    table.getRowFormatter().setStyleName(i + 2, "nfsetrodd");

                    for (int j = 0; j < temp.stats[i].length; j++) {
                        if (j > 0)
                            html += ",";
                        html += temp.stats[i][j];
                    }
                    html += "\" />";

                    int idx2 = -1;

                    for (int x = 0; x < temp.colValues[i].length; x++) {
                        table.setHTML(i + 2, ++idx2, temp.colValues[i][x]);
                        formatter.addStyleName(i + 2, idx2, "nfsetd");
                    }

                    // if (tempField == NetFSEClient.FIELD_DST_PORT)
                    // formatter.addStyleName(i + 2, 0, "tdright");
                    table.setHTML(i + 2, ++idx2, "" + temp.stats[i][0]);
                    formatter.addStyleName(i + 2, idx2, "tdright");
                    formatter.addStyleName(i + 2, idx2, "nfsetd");
                    table.setHTML(i + 2, ++idx2, html);
                    formatter.addStyleName(i + 2, idx2, "nfsetd");
                    table.setHTML(i + 2, ++idx2, "" + temp.stats[i][temp.stats[i].length - 1]);
                    formatter.addStyleName(i + 2, idx2, "nfsetd");
                    table.setHTML(i + 2, ++idx2, "" + temp.lows[i]);
                    formatter.addStyleName(i + 2, idx2, "nfsetd");
                    formatter.addStyleName(i + 2, idx2, "tdright");
                    table.setHTML(i + 2, ++idx2, "" + temp.highs[i]);
                    formatter.addStyleName(i + 2, idx2, "tdright");
                    formatter.addStyleName(i + 2, idx2, "nfsetd");
                    table.setHTML(i + 2, ++idx2, "" + temp.totals[i]);
                    formatter.addStyleName(i + 2, idx2, "tdright");
                    formatter.addStyleName(i + 2, idx2, "nfsetd");
                    table.setHTML(i + 2, ++idx2, "" + temp.percents[i] + "");
                    formatter.addStyleName(i + 2, idx2, "tdright");
                    formatter.addStyleName(i + 2, idx2, "nfsetd");
                }

            }
        };
        summaryStatusLabel.setText("Request in progress, please wait.");
        nfseService.getTopValues(fields, 10, getWhere(), callback);
    }

    public void setOffset(int offset) {
        this.offsets = offset;
    }

    public void setOrderBy(String orderBy) {
        this.orderBy = orderBy;
    }

    public String getWhere() {
        return where;
    }

    private void hideSummary() {
        FlexTable table = summaryDataTable;
        table.setVisible(false);
    }

    private void hideTable() {
        FlexTable table = getTable();
        table.setVisible(false);
    }

    private void initResultTable(FlexTable table, FlexTable dataTable, String[] colNames, String[] colFields) {
        // Build header
        FlexTable.FlexCellFormatter formatter = dataTable.getFlexCellFormatter();
        // dataTable.setBorderWidth(1);
        FlexTable nav = new FlexTable();

        // HorizontalPanel nav = new HorizontalPanel();
        int idx = -1;
        nav.setWidget(0, ++idx, firstLink);
        nav.setHTML(0, ++idx, "|");
        nav.setWidget(0, ++idx, nextLink);
        nav.setHTML(0, ++idx, "|");
        nav.setWidget(0, ++idx, prevLink);
        nav.setHTML(0, ++idx, "|");
        nav.setWidget(0, ++idx, lastLink);
        nav.setHTML(0, ++idx, "|");
        nav.setWidget(0, ++idx, deleteLink);
        nav.setHTML(0, ++idx, "|");
        nav.setWidget(0, ++idx, exportLink);
        nav.setHTML(0, ++idx, "|");
        nav.setWidget(0, ++idx, optionLink);
        nav.setHTML(0, ++idx, "| <B>Status:</b>");
        nav.setWidget(0, ++idx, statusLabel);

        FlexTable typeHeaderTable = new FlexTable();

        typeHeaderTable.setHTML(0, 0, "<h2>Alert Analysis<h2>");
        typeHeaderTable.setHTML(0, 1, "[");
        typeHeaderTable.getFlexCellFormatter().addStyleName(0, 1, "tdbottom");
        typeHeaderTable.setWidget(0, 2, showHideLink);
        typeHeaderTable.getFlexCellFormatter().addStyleName(0, 2, "tdbottom");
        typeHeaderTable.setHTML(0, 3, "]");
        typeHeaderTable.getFlexCellFormatter().addStyleName(0, 3, "tdbottom");
        table.setWidget(0, 0, typeHeaderTable);
        table.setWidget(1, 0, nav);

        final String[] fields = colFields;

        dataTable.setStyleName("nfsetable");
        dataTable.addStyleName("nfsetbody");

        for (int i = 0; i < colNames.length; i++) {
            if (colFields[i] != null) {
                final String field = colFields[i];

                Hyperlink sortLink = new Hyperlink(colNames[i], colNames[i] + i);
                final String orderByTemp = orderBy;
                sortLink.setHTML("<b>" + colNames[i] + "</b>");

                sortLink.addClickListener(new ClickListener() {
                    public void onClick(Widget sender) {

                        String ob = optionDialog2.getOrderBy().trim();
                        if (ob.equals(field + " asc")) {
                            optionDialog2.setOrderBy(field + " desc");
                        } else {
                            optionDialog2.setOrderBy(field + " asc");
                        }
                        setOrderBy(optionDialog2.getOrderBy());
                        get(0);
                    }
                });
                dataTable.setWidget(0, i, sortLink);
            } else {
                dataTable.setHTML(0, i, "<b>" + colNames[i] + "</b>");
            }
            formatter.setWordWrap(0, i, false);
            formatter.addStyleName(0, i, "tdleft");
        }

        dataTable.getRowFormatter().setStyleName(0, "nfseth");

        table.setWidget(2, 0, dataTable);
    }

    private void initSummaryTable(FlexTable table, FlexTable dataTable) {
        // Build header
        FlexTable.FlexCellFormatter formatter = dataTable.getFlexCellFormatter();
        FlexTable nav = new FlexTable();
        FlexTable checks = new FlexTable();

        int idx = -1;
        nav.setWidget(0, ++idx, refreshSummaryLink);
        nav.setHTML(0, ++idx, "| <B>Status:</b>");
        nav.setWidget(0, ++idx, summaryStatusLabel);
        int idx2 = -1;
        checks.setWidget(0, ++idx2, messageCheckBox);
        checks.setWidget(0, ++idx2, srcipCheckBox);
        checks.setWidget(0, ++idx2, dstipCheckBox);
        checks.setWidget(0, ++idx2, srcportCheckBox);
        checks.setWidget(0, ++idx2, dstportCheckBox);
        checks.setWidget(0, ++idx2, protocolCheckBox);

        FlexTable typeHeaderTable = new FlexTable();

        typeHeaderTable.setHTML(0, 0, "<h2>Alert Summary<h2>");
        typeHeaderTable.setHTML(0, 1, "[");
        typeHeaderTable.getFlexCellFormatter().addStyleName(0, 1, "tdbottom");
        typeHeaderTable.setWidget(0, 2, showHideSummaryLink);
        typeHeaderTable.getFlexCellFormatter().addStyleName(0, 2, "tdbottom");
        typeHeaderTable.setHTML(0, 3, "]");
        typeHeaderTable.getFlexCellFormatter().addStyleName(0, 3, "tdbottom");
        table.setWidget(0, 0, typeHeaderTable);
        table.setWidget(2, 0, nav);
        table.setWidget(3, 0, checks);

        // dataTable.setStyleName("nfsetable");
        // dataTable.addStyleName("nfsetbody");

        // dataTable.getRowFormatter().setStyleName(0, "nfseth");

        table.setWidget(4, 0, dataTable);
    }

    public void updateOptions(String where, String orderBy, int n) {

        this.where = where;

        this.orderBy = orderBy;
        this.n = n;
        this.get(0);
    }

    public void setAnalysisOptions(String where, String orderBy, int n) {

        this.where = where;

        this.orderBy = orderBy;
        this.n = n;
        this.get(0);
    }

    public void setRecordCount(int offset) {
        recordCount = offset;
    }

    public void setTypes() {

        refreshSummaryLink = new Hyperlink("Refresh", "Refresh");
        // showHideLinks[i].setText("Hide");
        refreshSummaryLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                summary();
            }
        });

        table = new FlexTable();

        showHideLink = new Hyperlink("Hide", "Hide");
        // showHideLinks[i].setText("Hide");
        showHideLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                String value = showHideLink.getText();
                if (value.equals("Show")) {
                    showHideLink.setText("Hide");
                    dataTable.setVisible(true);
                } else {
                    showHideLink.setText("Show");
                    dataTable.setVisible(false);
                }
            }
        });

        showHideSummaryLink = new Hyperlink("Hide", "Hide");
        // showHideLinks[i].setText("Hide");
        showHideSummaryLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                String value = showHideSummaryLink.getText();
                if (value.equals("Show")) {
                    showHideSummaryLink.setText("Hide");
                    summaryDataTable.setVisible(true);
                } else {
                    showHideSummaryLink.setText("Show");
                    summaryDataTable.setVisible(false);
                }
            }
        });

        dataTable = new FlexTable();
        summaryDataTable = new FlexTable();

        recordCount = 0;

        n = 15;
        firstLink = new Hyperlink("First", "First");
        firstLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                get(0);
            }
        });
        nextLink = new Hyperlink("Next", "Next");
        nextLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                int offset = getOffset() + getN();
                get(offset);
            }
        });
        prevLink = new Hyperlink("Prev", "Prev");
        prevLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                int offset = getOffset() - getN();
                if (offset < 0)
                    offset = 0;
                get(offset);
            }
        });
        lastLink = new Hyperlink("Last", "Last");
        lastLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                int offset = (getRecordCount() / getN()) * getN();
                get(offset);
            }
        });

        deleteLink = new Hyperlink("Delete", "Delete");
        deleteLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                MessageBox.show(new MessageBoxConfig() {
                    {
                        setTitle("Delete Alerts");
                        setMsg("Enter an SQL delete statement omitting the 'delete':");
                        setWidth(300);
                        setButtons(MessageBox.OKCANCEL);
                        setMultiline(true);
                        setCallback(new MessageBox.PromptCallback() {
                            public void execute(String btnID, String text) {
                                if (btnID.equals("ok"))
                                    delete(text);
                            }
                        });
                    }
                });

            }
        });

        exportLink = new Hyperlink("Export", "Export");
        exportLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                String url = "export?queryid=alerts&where=" + NetUtil.convertToHex(getWhere()) + "&orderby="
                        + getOrderBy();
                // System.out.println(url);

                Window.open(url, "Export", "");
            }
        });

        // optionDialogs[i] = new BrowseOptionsDialogBox(type, tempTypeName,
        // getSchema(type));
        optionDialog2 = new AlertOptionsDialog(this, getSchema());
        // optionDialogs[i].addPopupListener(this);
        where = "";
        recordCount = 0;

        optionLink = new Hyperlink("Options", "Options");
        optionLink.addClickListener(new ClickListener() {
            public void onClick(Widget sender) {
                // BrowseOptionsDialogBox popup = optionDialogs[typeIdx];
                // popup.setPopupPosition(sender.getAbsoluteLeft(),
                // sender.getAbsoluteTop());
                // popup.show();
                optionDialog2.show();
            }
        });

        statusLabel = new Label();
        statusLabel.setText("Idle");

        summaryStatusLabel = new Label();
        summaryStatusLabel.setText("Idle");

        summaryTable = new FlexTable();

        summaryTableByField = new FlexTable[1];
        summaryTableByField[0] = new FlexTable();

        summaryDataTable.setWidget(0, 0, summaryTableByField[0]);

        setupBrowseTable(this);

    }

    private void setupBrowseTable(FlexTable table) {
        while (table.getRowCount() > 0)
            table.removeRow(0);
        FlexTable.FlexCellFormatter formatter = table.getFlexCellFormatter();

        int idx = 0;

        table.setWidget(++idx, 0, this.table);
        table.setVisible(true);
        summaryTable.setWidget(2, 0, summaryDataTable);
        table.setWidget(++idx, 0, summaryTable);
        summaryTable.setVisible(true);

    }

    private void showSummary() {
        FlexTable table = summaryDataTable;
        if (!table.isVisible())
            table.setVisible(true);
    }

    private void showTable() {
        FlexTable table = getTable();
        if (!table.isVisible())
            table.setVisible(true);
    }

    private void summary() {
        String[] fields = getFields();
        summaryTable.setVisible(true);
        getTypeSummary(fields, true);

    }

    private String[] getFields() {
        Vector temp = new Vector();
        if (messageCheckBox.isChecked())
            temp.addElement("message");
        if (dstipCheckBox.isChecked())
            temp.addElement("dstip");
        if (srcipCheckBox.isChecked())
            temp.addElement("srcip");
        if (srcportCheckBox.isChecked())
            temp.addElement("srcport");
        if (dstportCheckBox.isChecked())
            temp.addElement("dstport");
        if (protocolCheckBox.isChecked())
            temp.addElement("protocol");

        if (temp.size() == 0) {
            messageCheckBox.setChecked(true);
            temp.addElement("message");
        }

        String[] fields = new String[temp.size()];
        for (int i = 0; i < fields.length; i++)
            fields[i] = (String) temp.elementAt(i);
        return fields;
    }

    private FlexTable getTable() {
        return table;
    }

    private void updateTable(FlexTable table, FlexTable dataTable, QueryResult qr) {

        FlexTable.FlexCellFormatter formatter = dataTable.getFlexCellFormatter();

        if (table.getRowCount() <= 1) {
            // Build header
            String[] colNames = { "", "Detect TS", "Start TS", "End TS", "Src IP", "Src Port", "Dst IP", "Dst Port",
                    "Protocol", "Message" };
            String[] colFields = { "", "detectts", "startts", "endts", "srcip", "srcport", "dstip", "dstport",
                    "protocol", "message" };
            initResultTable(table, dataTable, colNames, colFields);
            // System.out.println("Initialized result table.");
        }

        // while (dataTable.getRowCount() - 1 >
        // qr.flexRecordGroup.records.length)
        // dataTable.removeRow(dataTable.getRowCount() - 1);
        // while (dataTable.getRowCount() > 1)
        // dataTable.removeRow(dataTable.getRowCount() - 1);

        for (int i = 0; i < qr.alertFlexRecordGroup.records.length; i++) {
            int idx = -1;

            if (i % 2 == 0) {
                dataTable.getRowFormatter().setStyleName(i + 1, "nfsetr");
            } else {
                dataTable.getRowFormatter().setStyleName(i + 1, "nfsetrodd");
            }

            FlexRecord rec = qr.alertFlexRecordGroup.alerts[i];

            final FlexRecord tempRec = qr.alertFlexRecordGroup.records[i];

            Hyperlink viewLink = new Hyperlink();
            viewLink.setHTML("Details");
            viewLink.addClickListener(new ClickListener() {
                public void onClick(Widget sender) {
                    // eventDisplayDialog.setRecord(tempRec);
                    // eventDisplayDialog.show();
                    //EventViewerDialog eventDisplayDialog = new EventViewerDialog(tempRec);
                    //eventDisplayDialog.show();
                    TestDialog eventDisplayDialog = new TestDialog(tempRec);
                    eventDisplayDialog.show();
                }
            });

            dataTable.setWidget(i + 1, ++idx, viewLink);

            // System.out.println(rec);
            for (int x = 0; x < rec.values.length; x++) {
                idx++;
                formatter.addStyleName(i + 1, idx, "nfsetd");
                formatter.setWordWrap(i + 1, idx, false);
                switch (qr.alertFlexRecordGroup.flexRecordAlertFields[x].type) {
                case FlexRecordField.TYPE_FLOAT:
                    dataTable.setHTML(i + 1, idx, rec.values[x]);
                    formatter.addStyleName(i + 1, idx, "tdright");
                    break;
                case FlexRecordField.TYPE_INT:
                case FlexRecordField.TYPE_LONG:
                    switch (qr.alertFlexRecordGroup.flexRecordAlertFields[x].subType) {
                    case FlexRecordField.SUB_TYPE_BYTES:
                        if (rec.values[x].equals("-1"))
                            rec.values[x] = "-";
                        break;
                    }
                    dataTable.setHTML(i + 1, idx, rec.values[x]);
                    formatter.addStyleName(i + 1, idx, "tdright");
                    break;
                case FlexRecordField.TYPE_BOOLEAN:
                    if (qr.alertFlexRecordGroup.flexRecordAlertFields[x].subType == FlexRecordField.SUB_TYPE_CHECK_MARK) {
                        if (rec.values[x].equals("Y"))
                            dataTable.setHTML(i + 1, idx, "<img src=\"image/checkmark.gif\"/>");
                        else
                            dataTable.setHTML(i + 1, idx, "");
                    } else if (qr.alertFlexRecordGroup.flexRecordAlertFields[x].subType == FlexRecordField.SUB_TYPE_SOLERA_DRILL_DOWN) {
                        if (rec.values[x].equals("Y") && rec.specialValues != null && rec.specialValues.length > x
                                && rec.specialValues[x] != null) {
                            // final String url =
                            // "solera?format=tcpdump&sensorid=" + rec.sensorID
                            // + rec.specialValues;
                            final String url = "http://localhost:8080/nfse/solera?format=tcpdump&sensorid="
                                    + rec.sensorID + rec.specialValues[x];
                            // System.out.println(url);
                            Image img = new Image();
                            img.setUrl("image/play.gif");
                            img.addClickListener(new ClickListener() {
                                public void onClick(Widget sender) {
                                    Window.open(url, "_nfse_solera", null);
                                }
                            });
                            dataTable.setWidget(i + 1, idx, img);
                        } else {
                            dataTable.setHTML(i + 1, idx, "");
                        }
                    } else {
                        dataTable.setHTML(i + 1, idx, rec.values[x]);
                    }
                    break;
                default:

                    if (qr.alertFlexRecordGroup.flexRecordAlertFields[x].subType == FlexRecordField.SUB_TYPE_IP_ADDR) {
                        final String url = qr.alertFlexRecordGroup.ipLinkFactory.getURL(rec.values[x]);
                        if (url != null) {
                            Hyperlink ipLookup = new Hyperlink();
                            ipLookup.setHTML(rec.values[x]);
                            ipLookup.addClickListener(new ClickListener() {
                                public void onClick(Widget sender) {
                                    Window.open(url, "_nfse_iplookup", null);
                                }
                            });
                            dataTable.setWidget(i + 1, idx, ipLookup);
                        } else {
                            dataTable.setHTML(i + 1, idx, rec.values[x]);
                        }
                    } else {
                        dataTable.setHTML(i + 1, idx, rec.values[x]);
                    }
                    break;
                }

            }

        }

        while (dataTable.getRowCount() > qr.alertFlexRecordGroup.records.length + 1) {
            dataTable.removeRow(dataTable.getRowCount() - 1);
        }

        // dataTable.setVisible(false);
        // dataTable.setVisible(true);

    }
}
